{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Poincaré's bread\n",
    "\n",
    "Allen Downey\n",
    "\n",
    "[MIT License](https://en.wikipedia.org/wiki/MIT_License)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "sns.set(style='white')\n",
    "\n",
    "from thinkstats2 import Pmf, Cdf\n",
    "\n",
    "import thinkstats2\n",
    "import thinkplot\n",
    "\n",
    "decorate = thinkplot.config"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Poincaré's bread\n",
    "\n",
    "Henri Poincaré was a French mathematician who taught at the Sorbonne around 1900.The following anecdote about him is probably fabricated, but it makes an interesting probability problem.\n",
    "\n",
    "Supposedly, Poincaré suspected that his local bakery was selling loaves of bread that were lighter than the advertised weight of 1 kg, so every day for a year he bought a loaf of bread, brought it home and weighed it. At the end of the year, he plotted the distribution of his measurements and showed that it fit a normal distribution with mean 950 g and standard deviation 50 g. He brought this evidence to the bread police, who gave the baker a warning.\n",
    "\n",
    "For the next year, Poincaré continued the practice of weighing his bread every day. At the end of the year, he found that the average weight was 1,000 g, just as it should be, but again he complained to the bread police, and this time they fined the baker.\n",
    "\n",
    "Why? Because the shape of the distribution was asymmetric. Unlike the normal distribution, it was skewed to the right, which is consistent with the hypothesis that the baker was still making 950 g loaves, but deliberately giving Poincaré the heavier ones.\n",
    "\n",
    "Write a program that simulates a baker who chooses `n` loaves from a distribution with mean 950 g and standard deviation 50 g, and gives the heaviest one to Poincaré. What value of `n` yields a distribution with mean 1000 g? What is the standard deviation?\n",
    "\n",
    "Compare this distribution to a normal distribution with the same mean and the same standard deviation. Is the difference in the shape of the distribution big enough to convince the bread police?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "First, I'll make a function that simulates choosing `n` loaves and giving Poincaré the heaviest."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def choose_bread(mean, std, n):\n",
    "    loaves = np.random.normal(mean, std, size=n)\n",
    "    return max(loaves)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "mean = 950\n",
    "std = 50\n",
    "n = 5\n",
    "\n",
    "choose_bread(mean, std, n)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here's a sample from the distribution of bread weight if the baker chooses 5 loaves."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sample = [choose_bread(mean, std, n) for i in range(10000)]\n",
    "np.mean(sample)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And here's how the observed mean depends on `n`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for n in range(1, 10):\n",
    "    sample = [choose_bread(mean, std, n) for i in range(10000)]\n",
    "    print(n, np.mean(sample))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Looks like `n=4` yields a measured mean close to 1000 g.\n",
    "\n",
    "Here's a large sample of bread weights with `n=4` so we can estimate the mean and standard deviation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "n = 4\n",
    "sample = [choose_bread(mean, std, n) for i in range(10000)]\n",
    "\n",
    "mu = np.mean(sample)\n",
    "sigma = np.std(sample)\n",
    "mu, sigma"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now let's compare the distribution of the sample to the normal distribution with the same mean and std."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from scipy.stats import norm\n",
    "xs = sample.copy()\n",
    "xs.sort()\n",
    "ys = norm.cdf(xs, mu, sigma)\n",
    "\n",
    "plt.plot(xs, ys, color='gray', label='Gaussian model')\n",
    "cdf = Cdf(sample, label='Sample with n=4')\n",
    "thinkplot.Plot(cdf)\n",
    "decorate(xlabel='Weight in g', ylabel='CDF', title='Distribution of bread weight')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Visually they are almost indistinguishable, which makes it seem unlikely that Poincaré could really tell the difference, especially with only 365 observations.\n",
    "\n",
    "But let's look more closely.  First, let's simulate one year."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def simulate_year(mean, std, n, days):\n",
    "    sample = [choose_bread(mean, std, n) for i in range(days)]\n",
    "    return sample"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As a test statistic, we'll use the sample skew."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from scipy.stats import skew\n",
    "\n",
    "def test_stat(sample):\n",
    "    return skew(sample)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The null hypothesis is that the data come from a normal distribution with the observed mean and standard deviation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def run_model(mu, sigma, days):\n",
    "    return np.random.normal(mu, sigma, size=days)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we can generate fake data under the null hypothesis and compute the test statistic."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test_stat(run_model(mu, sigma, 365))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And we can estimate the distribution of the test statistic under the null hypothesis:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "skew_under_null = [test_stat(run_model(mu, sigma, 365)) for i in range(1000)]\n",
    "cdf = Cdf(skew_under_null)\n",
    "thinkplot.Cdf(cdf)\n",
    "decorate(xlabel='Skew', ylabel='CDF', title='Distribution of skew under H0')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here's the 95th percentile of the test statistic under the null hypothesis."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "thresh = np.percentile(skew_under_null, 95)\n",
    "thresh"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If Herni observes a skew above this threshold, he would conclude that it is statistically significant.\n",
    "\n",
    "Let's see how often that would happen under the alternate hypothesis, that they baker is giving him the heaviest of 4 loaves."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "n = 4\n",
    "skew_poincare = [test_stat(simulate_year(mean, std, n, 365)) for i in range(1000)]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here's what the sampling distribution looks like for the skew Poincaré observes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cdf = Cdf(skew_poincare)\n",
    "thinkplot.Cdf(cdf)\n",
    "decorate(xlabel='Skew', ylabel='CDF', title='Distribution of skew if the baker cheats n=4')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If Poincaré runs this experiment for a year, what is the chance he gets a statistically significant result?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "np.mean(skew_poincare > thresh)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This probability is the power of the test.  In this example, it is 60-70%, which is not terrible.  As a very general guideline, statisticians recommend designing experiments with a power of about 80%.\n",
    "\n",
    "For how many days would Poincaré have to weigh his bread to get a power of 80%?"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
